//
//  ShareDetailsViewController.m
//  phmall
//
//  Created by admin on 2017/12/9.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "ShareDetailsViewController.h"
#import "ShareDetailsView.h"
#import "CommodityDetailsVC.h"
#import "RecommendView.h"
#import "ShareModel.h"
#import "GoodsModel.h"
@interface ShareDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,ShareDetailsViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    UIView *headerView;
    RecommendView *recommend;
    ShareDetailsView *detailsView;
}
@property(strong,nonatomic)UITableView *myTableview;
@property(strong,nonatomic)ShareModel *model;
@property(nonatomic,strong)NSMutableArray *likeArry;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation ShareDetailsViewController

-(void)likeAction:(NSString *)uid{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSMutableArray *likeArray=[[NSMutableArray alloc]init];
    id obj=[ud objectForKey:@"like"];
    if (obj)
    {
        for (NSString *str in obj) {
            [likeArray addObject:str];
        }
    }

    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"share/love"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSString *data=responseDict[@"data"];
                if ([data isEqualToString:@"1"]) {
                    if (![likeArray containsObject:uid]) {
                        [likeArray addObject:uid];
                    }
                    NSArray *like=[NSArray arrayWithArray:likeArray];
                    [ud setObject:like forKey:@"like"];
                }else{
                    NSLog(@"点赞失败");
                }
            }
        }
        [self loadDataWithShareDetail];
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        //        [SVProgressHUD showErrorWithStatus:Localized(@"网络错误")];
    }];
}
-(void)addFriends:(NSString *)uid{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"share/friend"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                NSString *data=[NSString stringWithFormat:@"%@",responseDict[@"data"]];
                if ([data isEqualToString:@"1"]) {
                    NSLog(@"添加成功");
                    [PublicClass ProgressHUDModeText:Localized(@"添加成功") andTime:2 ];
                }else{
                    NSLog(@"添加失败");
                    [PublicClass ProgressHUDModeText:Localized(@"添加失败") andTime:2 ];
                }
            }
        }else{
            [self userLogout];
//            [PublicClass ProgressHUDModeText:@"账号未登录或登录已过期" andTime:2];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        //        [SVProgressHUD showErrorWithStatus:Localized(@"网络错误")];
    }];
}
-(void)purchase:(NSString *)uid{
        self.hidesBottomBarWhenPushed=YES;
        CommodityDetailsVC *sear=[[CommodityDetailsVC alloc] init];
        sear.uid=uid;
        [self.navigationController pushViewController:sear animated:YES];
        self.hidesBottomBarWhenPushed=NO;
}
- (void)loadDataWithShareDetail{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"share/detail"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                [self analysisDataWithShareArray:responseDict[@"data"]];
            }
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}

- (void)analysisDataWithShareArray:(NSMutableArray *)array{
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    NSArray *likeArray;
    id obj=[ud objectForKey:@"like"];
    if (obj)
    {
        likeArray=(NSMutableArray *)obj;
    }
    for (NSDictionary *dict in array) {
        self.model = [ShareModel yy_modelWithDictionary:dict];
        self.model.like=NO;
        if ([likeArray containsObject:self.model.uid]) {
            self.model.like=YES;
        }
    }
    detailsView.model=self.model;
    CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headerView.bounds;
    frame.size.height = height;
    headerView.frame = frame;
    [self.myTableview setTableHeaderView:headerView];
    [headerView layoutIfNeeded];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;

    self.title=Localized(@"详情");
    self.emptyType=EmptyDataSetNone;
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(self.tabBar_height);
    }];
    [self loadDataWithShareDetail];
    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //轮播图

    detailsView=[[ShareDetailsView alloc]init];
    detailsView.delegate=self;
    [headerView addSubview:detailsView];
    [detailsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
//        make.height.offset(70+SCREEN_WIDTH);
        make.bottom.equalTo(detailsView.like.mas_bottom).offset(10);
        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10).priorityHigh();
    }];
    [detailsView layoutIfNeeded];
    // Do any additional setup after loading the view.
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 0;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;;
    }
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.emptyType==EmptyDataSetNoNetwork){
        return [UIImage imageNamed:@"断网"];
    }
    return nil;
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    if(self.emptyType==EmptyDataSetNoNetwork){
        return NO;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
    
    if(self.emptyType==EmptyDataSetNoNetwork){
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithShareDetail];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}
- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}
//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource = self;
        _myTableview.emptyDataSetDelegate = self;
    }
    return _myTableview;
}
-(NSMutableArray *)likeArry{
    if (!_likeArry) {
        _likeArry=[[NSMutableArray alloc] init];
    }
    return _likeArry;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
